from django.shortcuts import render
from .models import UserModel,SortsModel,GoodsModel,BrowseModel
from rest_framework.views import APIView
from rest_framework.response import Response
from .serial import BrowseSerializer
import datetime
from django.utils import timezone
import csv
from tools.myredis import r
import os,json
from django.conf import settings
from tools.similarty import rec
from tools.ell import el
# Create your views here.


class RecommendView(APIView):

    def get(self,request):
        user_id = int(self.request.query_params.get('user_id'))
        rec_user = r.get_str(f'rec{user_id}')
        if rec_user:
            data = json.loads(rec_user)
            goods_list = [{"id":item['id'],"name":item['name']} for item in data]
            return Response({'code':200,'msg':'推荐成功','data':goods_list})
        else:
            res = rec(user_id)
            data = GoodsModel.objects.filter(id__in=res).values('id','name').order_by('-sales')
            goods_list = [{"id":item['id'],"name":item['name']} for item in data]
            r.setex_str(f'rec{user_id}',60,json.dumps(goods_list))
            return Response({'code':200,'msg':'推荐成功','data':goods_list})












class BrowseView(APIView):
    def post(self,request):
        user_id = self.request.data.get('user_id')
        goods_id = self.request.data.get('goods_id')
        data = BrowseModel.objects.filter(user_id=user_id,goods_id=goods_id).first()
        if data:
            data.create_time = timezone.now()
            data.count += 1
            data.save()
        else:
            goods_data = GoodsModel.objects.filter(id=goods_id).first()
            serial_data = {
                'user':user_id,
                'count':1,
                "goods":goods_data.id,
                "topid":goods_data.topid_id
            }
            ser = BrowseSerializer(data=serial_data)
            if ser.is_valid():
                ser.save()

        file_path = os.path.join(settings.BASE_DIR, 'csrec', 'recommend.csv')

        if not os.path.exists(file_path):
            # 如果文件不存在，则创建文件并写入列标题
            with open(file_path, 'w', newline='') as csvfile:
                writer = csv.writer(csvfile)
                writer.writerow(['userid', 'goodsid'])  # 写入列标题

            # 无论文件是否存在，都追加数据
        with open(file_path, 'a', newline='') as csvfile:
            writer = csv.writer(csvfile)
            writer.writerow([user_id, goods_id])  # 写入数据行


        return Response({'code':200,'msg':'浏览添加成功'})












class AddElasticSearch(APIView):

    def get(self,request):
        data = GoodsModel.objects.all().values('id','name','pid_id','topid_id')
        data_list = []
        for i in data:
            aa = {
                '_index':"shopping",
                '_id':i['id'],
                "_source":{
                    "id":i['id'],
                    'name':i['name'],
                    'pid':i['pid_id'],
                    'topid':i['topid_id']
                }
            }
            data_list.append(aa)
        el.add_documents(data_list)
        return Response({'code':200,'msg':'添加成功'})


class SearchGoodsView(APIView):

    def get(self,request):
        name= self.request.query_params.get('name', None)
        sales = int(self.request.query_params.get('sales', None))
        topid = int(self.request.query_params.get('topid', None))
        page = int(self.request.query_params.get('page', None))
        print(name,"==",sales,"==",topid,"==",page)
        res  = el.search(name,sales,topid,page)
        print(res)

        return Response({'code':200,'data':res[1],"total":res[0]})















